﻿using System;
using DHelpers.Exceptions;
using DomainModels.DomainModels.JsonModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Core.Helpers
{
    public class JsonHelper
    {
        public static T Json2Object<T>(string json) where T : class
        {
            var response = JObject.Parse(json);

            if (response["response"] != null)
                return response["response"].First != null
                    ? JsonConvert.DeserializeObject<T>(response["response"].First.ToString())
                    : JsonConvert.DeserializeObject<T>(response["response"].ToString());

            if (response["error"] != null)
                throw new JsonAppException(JsonConvert.DeserializeObject<Error>(response["error"].ToString()));
            return null;
        }

        public static string Object2Json(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
    }
}